package com.tedu.egweibo.controller;

import com.tedu.egweibo.common.result.JsonResult;
import com.tedu.egweibo.common.result.StatusCode;
import com.tedu.egweibo.mapper.UserMapper;
import com.tedu.egweibo.pojo.dto.UserLoginDTO;
import com.tedu.egweibo.pojo.dto.UserRegDTO;
import com.tedu.egweibo.pojo.entity.User;
import com.tedu.egweibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
@Api(tags = "用户模块")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation("用户注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO) {
        log.trace("用户注册");
        log.debug("userRegDTO:" + userRegDTO);
        User findUser = userMapper.selectByUsername(userRegDTO.getUsername());
        if (findUser != null) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        return JsonResult.success(userMapper.insert(user));
    }

    @PostMapping("login")
    @ApiOperation("用户登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userRegDTO:" + userLoginDTO);

        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userLoginDTO.getPassword())) {
                session.setAttribute("user", user);
                return JsonResult.success(user);
            } else {
                return new JsonResult(StatusCode.PASSWORD_ERROR);
            }
        } else {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
    }

    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        } else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return JsonResult.success(userVO);
        }
    }

    @ApiOperation("退出登录")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }

}
